





<!DOCTYPE html>
<html class="writer-html5" lang="zh-CN" >
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>在Android上部署预训练模型 &mdash; tvm 0.8.dev1982 文档</title>
  

  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/gallery.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/css/tlcpack_theme.css" type="text/css" />

  
  
    <link rel="shortcut icon" href="../../_static/tvm-logo-square.png"/>
  

  
  
  
  
    
      <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
        <script data-url_root="../../" id="documentation_options" src="../../_static/documentation_options.js"></script>
        <script src="../../_static/jquery.js"></script>
        <script src="../../_static/underscore.js"></script>
        <script src="../../_static/doctools.js"></script>
        <script src="../../_static/translations.js"></script>
    
    <script type="text/javascript" src="../../_static/js/theme.js"></script>

    
    <script type="text/javascript" src="../../_static/js/tlcpack_theme.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="在Raspberry Pi上部署预训练模型" href="deploy_model_on_rasp.html" />
    <link rel="prev" title="Deploy Deep Learning Models" href="index.html" /> 
</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">
    
    
<header class="header">
    <div class="innercontainer">
      <div class="headerInner d-flex justify-content-between align-items-center">
          <div class="headerLogo">
               <a href="https://tvm.apache.org/"><img src=https://tvm.apache.org/assets/images/logo.svg alt="logo"></a>
          </div>

          <div id="headMenu" class="headerNav">
            <button type="button" id="closeHeadMenu" class="navCloseBtn"><img src="../../_static/img/close-icon.svg" alt="Close"></button>
             <ul class="nav">
                <li class="nav-item">
                   <a class="nav-link" href=https://tvm.apache.org/community>Community</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://tvm.apache.org/download>Download</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://tvm.apache.org/vta>VTA</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://tvm.apache.org/blog>Blog</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://tvm.apache.org/docs>Docs</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://tvmconf.org>Conference</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://github.com/apache/tvm/>Github</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://tvmchinese.github.io/declaration_zh_CN.html>About-Translators</a>
                </li>
             </ul>
               <div class="responsivetlcdropdown">
                 <button type="button" class="btn-link">
                   ASF
                 </button>
                 <ul>
                     <li>
                       <a href=https://apache.org/>Apache Homepage</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/licenses/>License</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/foundation/sponsorship.html>Sponsorship</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/security/>Security</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/foundation/thanks.html>Thanks</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/events/current-event>Events</a>
                     </li>
                     <li>
                       <a href=https://www.zhihu.com/column/c_1429578595417563136>Zhihu</a>
                     </li>
                 </ul>
               </div>
          </div>
            <div class="responsiveMenuIcon">
              <button type="button" id="menuBtn" class="btn-menu"><img src="../../_static/img/menu-icon.svg" alt="Menu Icon"></button>
            </div>

            <div class="tlcDropdown">
              <div class="dropdown">
                <button type="button" class="btn-link dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                  ASF
                </button>
                <div class="dropdown-menu dropdown-menu-right">
                  <ul>
                     <li>
                       <a href=https://apache.org/>Apache Homepage</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/licenses/>License</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/foundation/sponsorship.html>Sponsorship</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/security/>Security</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/foundation/thanks.html>Thanks</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/events/current-event>Events</a>
                     </li>
                     <li>
                       <a href=https://www.zhihu.com/column/c_1429578595417563136>Zhihu</a>
                     </li>
                  </ul>
                </div>
              </div>
          </div>
       </div>
    </div>
 </header>
 
    <nav data-toggle="wy-nav-shift" class="wy-nav-side fixed">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search" >
          

          
            <a href="../../index.html">
          

          
            
            <img src="../../_static/tvm-logo-small.png" class="logo" alt="Logo"/>
          
          </a>

          
            
            
                <div class="version">
                  0.8.dev1982
                </div>
            
          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        
        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <p class="caption" role="heading"><span class="caption-text">如何开始</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../install/index.html">安装 TVM</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../contribute/index.html">贡献者指南</a></li>
</ul>
<p class="caption" role="heading"><span class="caption-text">用户引导</span></p>
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../../tutorial/index.html">User Tutorial</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="../index.html">How To Guides</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="../compile_models/index.html">编译深度学习模型</a></li>
<li class="toctree-l2 current"><a class="reference internal" href="../deploy/index.html">TVM 部署模型和集成</a><ul class="current">
<li class="toctree-l3"><a class="reference internal" href="../deploy/index.html#build-the-tvm-runtime-library">构建 TVM 运行 runtime 库</a></li>
<li class="toctree-l3"><a class="reference internal" href="../deploy/index.html#cross-compile-the-tvm-runtime-for-other-architectures">为其它架构交叉编译TVM runtime</a></li>
<li class="toctree-l3"><a class="reference internal" href="../deploy/index.html#optimize-and-tune-models-for-target-devices">针对目标设备优化和调整模型</a></li>
<li class="toctree-l3"><a class="reference internal" href="../deploy/index.html#deploy-optimized-model-on-target-devices">在目标设备上部署优化的模型</a></li>
<li class="toctree-l3 current"><a class="reference internal" href="../deploy/index.html#additional-deployment-how-tos">其他部署方式</a><ul class="current">
<li class="toctree-l4 current"><a class="reference internal" href="index.html">Deploy Deep Learning Models</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../work_with_relay/index.html">Work With Relay</a></li>
<li class="toctree-l2"><a class="reference internal" href="../work_with_schedules/index.html">Work With Tensor Expression and Schedules</a></li>
<li class="toctree-l2"><a class="reference internal" href="../optimize_operators/index.html">优化张量算子</a></li>
<li class="toctree-l2"><a class="reference internal" href="../tune_with_autotvm/index.html">Auto-Tune with Templates and AutoTVM</a></li>
<li class="toctree-l2"><a class="reference internal" href="../tune_with_autoscheduler/index.html">Use AutoScheduler for Template-Free Scheduling</a></li>
<li class="toctree-l2"><a class="reference internal" href="../work_with_microtvm/index.html">Work With microTVM</a></li>
<li class="toctree-l2"><a class="reference internal" href="../extend_tvm/index.html">Extend TVM</a></li>
<li class="toctree-l2"><a class="reference internal" href="../profile/index.html">Profile Models</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../errors.html">Handle TVM Errors</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../faq.html">常见提问</a></li>
</ul>
</li>
</ul>
<p class="caption" role="heading"><span class="caption-text">开发者引导</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../dev/tutorial/index.html">Developer Tutorial</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../dev/how_to/how_to.html">开发者指南</a></li>
</ul>
<p class="caption" role="heading"><span class="caption-text">架构指南</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../arch/index.html">Design and Architecture</a></li>
</ul>
<p class="caption" role="heading"><span class="caption-text">主题引导</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../topic/microtvm/index.html">microTVM：裸机使用TVM</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../topic/vta/index.html">VTA: Versatile Tensor Accelerator</a></li>
</ul>
<p class="caption" role="heading"><span class="caption-text">参考指南</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../reference/langref/index.html">语言参考</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../reference/api/python/index.html">Python API</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../reference/api/links.html">Other APIs</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../reference/publications.html">Publications</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../genindex.html">索引</a></li>
</ul>

            
          
        </div>
        
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
      
      <nav class="wy-nav-top" aria-label="top navigation" data-toggle="wy-nav-top">
        
            <div class="togglemenu">

            </div>
            <div class="nav-content">
              <!-- tvm -->
              Table of content
            </div>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        

          




















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../../index.html">Docs</a> <span class="br-arrow">></span></li>
        
          <li><a href="../index.html">How To Guides</a> <span class="br-arrow">></span></li>
        
          <li><a href="../deploy/index.html">TVM 部署模型和集成</a> <span class="br-arrow">></span></li>
        
          <li><a href="index.html">Deploy Deep Learning Models</a> <span class="br-arrow">></span></li>
        
      <li>在Android上部署预训练模型</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
            
            <a href="../../_sources/how_to/deploy_models/deploy_model_on_android.rst.txt" rel="nofollow"> <img src="../../_static//img/source.svg" alt="viewsource"/></a>
          
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <div class="sphx-glr-download-link-note admonition note">
<p class="admonition-title">注解</p>
<p>点击 <a class="reference internal" href="#sphx-glr-download-how-to-deploy-models-deploy-model-on-android-py"><span class="std std-ref">这里</span></a> 下载完整的样例代码</p>
</div>
<div class="sphx-glr-example-title section" id="deploy-the-pretrained-model-on-android">
<span id="tutorial-deploy-model-on-android"></span><span id="sphx-glr-how-to-deploy-models-deploy-model-on-android-py"></span><h1>在Android上部署预训练模型<a class="headerlink" href="#deploy-the-pretrained-model-on-android" title="永久链接至标题">¶</a></h1>
<p><strong>作者</strong>: <a class="reference external" href="https://tkat0.github.io/">Tomohiro Kato</a></p>
<p>这是一个使用Relay编译keras模型并将其部署到Android设备上的示例。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">from</span> <span class="nn">PIL</span> <span class="k">import</span> <span class="n">Image</span>
<span class="kn">import</span> <span class="nn">keras</span>
<span class="kn">from</span> <span class="nn">keras.applications.mobilenet_v2</span> <span class="k">import</span> <span class="n">MobileNetV2</span>
<span class="kn">import</span> <span class="nn">tvm</span>
<span class="kn">from</span> <span class="nn">tvm</span> <span class="k">import</span> <span class="n">te</span>
<span class="kn">import</span> <span class="nn">tvm.relay</span> <span class="k">as</span> <span class="nn">relay</span>
<span class="kn">from</span> <span class="nn">tvm</span> <span class="k">import</span> <span class="n">rpc</span>
<span class="kn">from</span> <span class="nn">tvm.contrib</span> <span class="k">import</span> <span class="n">utils</span><span class="p">,</span> <span class="n">ndk</span><span class="p">,</span> <span class="n">graph_executor</span> <span class="k">as</span> <span class="n">runtime</span>
<span class="kn">from</span> <span class="nn">tvm.contrib.download</span> <span class="k">import</span> <span class="n">download_testdata</span>
</pre></div>
</div>
<div class="section" id="setup-environment">
<h2>设置环境<a class="headerlink" href="#setup-environment" title="永久链接至标题">¶</a></h2>
<p>由于Android有许多必需的软件包，因此建议使用官方的Docker映像。</p>
<p>首先，要构建和运行Docker映像，我们可以运行以下命令。</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span>git clone --recursive https://github.com/apache/tvm tvm
<span class="nb">cd</span> tvm
docker build -t tvm.demo_android -f docker/Dockerfile.demo_android ./docker
docker run --pid<span class="o">=</span>host -h tvm -v <span class="nv">$PWD</span>:/workspace <span class="se">\</span>
       -w /workspace -p <span class="m">9190</span>:9190 --name tvm -it tvm.demo_android bash
</pre></div>
</div>
<p>您现在在容器内。克隆的TVM目录安装在/workspace上。此时，准备一下稍后描述的RPC使用的9190端口。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>请在容器中执行以下步骤。我们可以执行:code:<a href="#id1"><span class="problematic" id="id2">`</span></a>docker exec -it tvm bash`在容器中打开一个新的终端。</p>
</div>
<p>接下来我们构建 TVM。</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span>mkdir build
<span class="nb">cd</span> build
cmake -DUSE_LLVM<span class="o">=</span>llvm-config-8 <span class="se">\</span>
      -DUSE_RPC<span class="o">=</span>ON <span class="se">\</span>
      -DUSE_SORT<span class="o">=</span>ON <span class="se">\</span>
      -DUSE_VULKAN<span class="o">=</span>ON <span class="se">\</span>
      -DUSE_GRAPH_EXECUTOR<span class="o">=</span>ON <span class="se">\</span>
      ..
make -j10
</pre></div>
</div>
<p>成功构建 TVM 后，请设置 PYTHONPATH。</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="nb">echo</span> <span class="s1">&#39;export PYTHONPATH=/workspace/python:/workspace/vta/python:${PYTHONPATH}&#39;</span> &gt;&gt; ~/.bashrc
<span class="nb">source</span> ~/.bashrc
</pre></div>
</div>
</div>
<div class="section" id="start-rpc-tracker">
<h2>启动 RPC 跟踪器<a class="headerlink" href="#start-rpc-tracker" title="永久链接至标题">¶</a></h2>
<p>TVM 使用 RPC 会话与安卓设备进行通信。</p>
<p>要启动RPC跟踪器，请在容器中运行此命令。在整个调谐过程中需要跟踪器，因此我们需要为此命令打开一个新的终端：</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span>python3 -m tvm.exec.rpc_tracker --host<span class="o">=</span><span class="m">0</span>.0.0.0 --port<span class="o">=</span><span class="m">9190</span>
</pre></div>
</div>
<p>预期输出是</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span>INFO:RPCTracker:bind to <span class="m">0</span>.0.0.0:9190
</pre></div>
</div>
</div>
<div class="section" id="register-android-device-to-rpc-tracker">
<h2>将安卓设备注册到 RPC 跟踪器<a class="headerlink" href="#register-android-device-to-rpc-tracker" title="永久链接至标题">¶</a></h2>
<p>现在我们可以将我们的安卓设备注册到跟踪器上。</p>
<p>请点击`自述页面 &lt;<a class="reference external" href="https://github.com/apache/tvm/tree/main/apps/android_rpc">https://github.com/apache/tvm/tree/main/apps/android_rpc</a>&gt;`_在android设备上安装TVM RPC APK。</p>
<p>下面是config.mk 的例子。我启用了Opencl和Vulkan。</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="nv">APP_ABI</span> <span class="o">=</span> arm64-v8a

<span class="nv">APP_PLATFORM</span> <span class="o">=</span> android-24

<span class="c1"># whether enable OpenCL during compile</span>
<span class="nv">USE_OPENCL</span> <span class="o">=</span> <span class="m">1</span>

<span class="c1"># whether to enable Vulkan during compile</span>
<span class="nv">USE_VULKAN</span> <span class="o">=</span> <span class="m">1</span>

ifeq <span class="o">(</span><span class="k">$(</span>USE_VULKAN<span class="k">)</span>, <span class="m">1</span><span class="o">)</span>
  <span class="c1"># Statically linking vulkan requires API Level 24 or higher</span>
  <span class="nv">APP_PLATFORM</span> <span class="o">=</span> android-24
endif

<span class="c1"># the additional include headers you want to add, e.g., SDK_PATH/adrenosdk/Development/Inc</span>
<span class="nv">ADD_C_INCLUDES</span> <span class="o">+=</span> /work/adrenosdk-linux-5_0/Development/Inc
<span class="c1"># downloaded from https://github.com/KhronosGroup/OpenCL-Headers</span>
<span class="nv">ADD_C_INCLUDES</span> <span class="o">+=</span> /usr/local/OpenCL-Headers/

<span class="c1"># the additional link libs you want to add, e.g., ANDROID_LIB_PATH/libOpenCL.so</span>
<span class="nv">ADD_LDLIBS</span> <span class="o">=</span> /workspace/pull-from-android-device/libOpenCL.so
</pre></div>
</div>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>此时，别忘了`创建一个独立的工具链&lt;<a class="reference external" href="https://github.com/apache/tvm/tree/main/apps/android_rpc#architecture-and-android-standalone-toolchain">https://github.com/apache/tvm/tree/main/apps/android_rpc#architecture-and-android-standalone-toolchain</a>&gt;`_ .。</p>
<p>例如</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="nv">$ANDROID_NDK_HOME</span>/build/tools/make-standalone-toolchain.sh <span class="se">\</span>
   --platform<span class="o">=</span>android-24 --use-llvm --arch<span class="o">=</span>arm64 --install-dir<span class="o">=</span>/opt/android-toolchain-arm64
<span class="nb">export</span> <span class="nv">TVM_NDK_CC</span><span class="o">=</span>/opt/android-toolchain-arm64/bin/aarch64-linux-android-g++
</pre></div>
</div>
</div>
<p>接下来，启动Android应用程序并输入RPC Tracker的IP地址和端口。然后您就注册好了您的设备。</p>
<p>注册设备后，我们可以通过查询rpc_tracker确认</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span>python3 -m tvm.exec.query_rpc_tracker --host<span class="o">=</span><span class="m">0</span>.0.0.0 --port<span class="o">=</span><span class="m">9190</span>
</pre></div>
</div>
<p>例如，如果我们有 1 个安卓设备。输出是</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span>Queue Status
----------------------------------
key          total  free  pending
----------------------------------
android      <span class="m">1</span>      <span class="m">1</span>     <span class="m">0</span>
----------------------------------
</pre></div>
</div>
<p>要确认您可以与 Android 通信，我们可以按照测试脚本运行。如果您使用 OpenCL 和 Vulkan，请在脚本中设置:code:<cite>test_opencl</cite> 和:code:<cite>test_vulkan</cite></p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="nb">export</span> <span class="nv">TVM_TRACKER_HOST</span><span class="o">=</span><span class="m">0</span>.0.0.0
<span class="nb">export</span> <span class="nv">TVM_TRACKER_PORT</span><span class="o">=</span><span class="m">9190</span>
</pre></div>
</div>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="nb">cd</span> /workspace/apps/android_rpc
python3 tests/android_rpc_test.py
</pre></div>
</div>
</div>
<div class="section" id="load-pretrained-keras-model">
<h2>加载预训练 Keras 模型<a class="headerlink" href="#load-pretrained-keras-model" title="永久链接至标题">¶</a></h2>
<p>我们加载keras提供的预先训练过的MobileNetV2(alpha=0.5)分类模型。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">keras</span><span class="o">.</span><span class="n">backend</span><span class="o">.</span><span class="n">clear_session</span><span class="p">()</span>  <span class="c1"># Destroys the current TF graph and creates a new one.</span>
<span class="n">weights_url</span> <span class="o">=</span> <span class="s2">&quot;&quot;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span>
    <span class="p">[</span>
        <span class="s2">&quot;https://github.com/JonathanCMitchell/&quot;</span><span class="p">,</span>
        <span class="s2">&quot;mobilenet_v2_keras/releases/download/v1.1/&quot;</span><span class="p">,</span>
        <span class="s2">&quot;mobilenet_v2_weights_tf_dim_ordering_tf_kernels_0.5_224.h5&quot;</span><span class="p">,</span>
    <span class="p">]</span>
<span class="p">)</span>
<span class="n">weights_file</span> <span class="o">=</span> <span class="s2">&quot;mobilenet_v2_weights.h5&quot;</span>
<span class="n">weights_path</span> <span class="o">=</span> <span class="n">download_testdata</span><span class="p">(</span><span class="n">weights_url</span><span class="p">,</span> <span class="n">weights_file</span><span class="p">,</span> <span class="n">module</span><span class="o">=</span><span class="s2">&quot;keras&quot;</span><span class="p">)</span>
<span class="n">keras_mobilenet_v2</span> <span class="o">=</span> <span class="n">MobileNetV2</span><span class="p">(</span>
    <span class="n">alpha</span><span class="o">=</span><span class="mf">0.5</span><span class="p">,</span> <span class="n">include_top</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">weights</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">input_shape</span><span class="o">=</span><span class="p">(</span><span class="mi">224</span><span class="p">,</span> <span class="mi">224</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="n">classes</span><span class="o">=</span><span class="mi">1000</span>
<span class="p">)</span>
<span class="n">keras_mobilenet_v2</span><span class="o">.</span><span class="n">load_weights</span><span class="p">(</span><span class="n">weights_path</span><span class="p">)</span>
</pre></div>
</div>
<p>为了测试我们的模型，在这里我们下载了猫的图像，并改变其格式。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">img_url</span> <span class="o">=</span> <span class="s2">&quot;https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true&quot;</span>
<span class="n">img_name</span> <span class="o">=</span> <span class="s2">&quot;cat.png&quot;</span>
<span class="n">img_path</span> <span class="o">=</span> <span class="n">download_testdata</span><span class="p">(</span><span class="n">img_url</span><span class="p">,</span> <span class="n">img_name</span><span class="p">,</span> <span class="n">module</span><span class="o">=</span><span class="s2">&quot;data&quot;</span><span class="p">)</span>
<span class="n">image</span> <span class="o">=</span> <span class="n">Image</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">img_path</span><span class="p">)</span><span class="o">.</span><span class="n">resize</span><span class="p">((</span><span class="mi">224</span><span class="p">,</span> <span class="mi">224</span><span class="p">))</span>
<span class="n">dtype</span> <span class="o">=</span> <span class="s2">&quot;float32&quot;</span>


<span class="k">def</span> <span class="nf">transform_image</span><span class="p">(</span><span class="n">image</span><span class="p">):</span>
    <span class="n">image</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="n">image</span><span class="p">)</span> <span class="o">-</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mf">123.0</span><span class="p">,</span> <span class="mf">117.0</span><span class="p">,</span> <span class="mf">104.0</span><span class="p">])</span>
    <span class="n">image</span> <span class="o">/=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mf">58.395</span><span class="p">,</span> <span class="mf">57.12</span><span class="p">,</span> <span class="mf">57.375</span><span class="p">])</span>
    <span class="n">image</span> <span class="o">=</span> <span class="n">image</span><span class="o">.</span><span class="n">transpose</span><span class="p">((</span><span class="mi">2</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">))</span>
    <span class="n">image</span> <span class="o">=</span> <span class="n">image</span><span class="p">[</span><span class="n">np</span><span class="o">.</span><span class="n">newaxis</span><span class="p">,</span> <span class="p">:]</span>
    <span class="k">return</span> <span class="n">image</span>


<span class="n">x</span> <span class="o">=</span> <span class="n">transform_image</span><span class="p">(</span><span class="n">image</span><span class="p">)</span>
</pre></div>
</div>
<p>synset用于将标签从ImageNet类的数量转换为人类可以理解的单词。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">synset_url</span> <span class="o">=</span> <span class="s2">&quot;&quot;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span>
    <span class="p">[</span>
        <span class="s2">&quot;https://gist.githubusercontent.com/zhreshold/&quot;</span><span class="p">,</span>
        <span class="s2">&quot;4d0b62f3d01426887599d4f7ede23ee5/raw/&quot;</span><span class="p">,</span>
        <span class="s2">&quot;596b27d23537e5a1b5751d2b0481ef172f58b539/&quot;</span><span class="p">,</span>
        <span class="s2">&quot;imagenet1000_clsid_to_human.txt&quot;</span><span class="p">,</span>
    <span class="p">]</span>
<span class="p">)</span>
<span class="n">synset_name</span> <span class="o">=</span> <span class="s2">&quot;imagenet1000_clsid_to_human.txt&quot;</span>
<span class="n">synset_path</span> <span class="o">=</span> <span class="n">download_testdata</span><span class="p">(</span><span class="n">synset_url</span><span class="p">,</span> <span class="n">synset_name</span><span class="p">,</span> <span class="n">module</span><span class="o">=</span><span class="s2">&quot;data&quot;</span><span class="p">)</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">synset_path</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="n">synset</span> <span class="o">=</span> <span class="nb">eval</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">())</span>
</pre></div>
</div>
</div>
<div class="section" id="compile-the-model-with-relay">
<h2>通过 Realy 编译模型<a class="headerlink" href="#compile-the-model-with-relay" title="永久链接至标题">¶</a></h2>
<p>如果我们在x86服务器上运行这个示例进行演示，我们只需将其设置为 <code class="code docutils literal notranslate"><span class="pre">llvm</span></code>。如果在Android设备上运行它，我们需要指定它的指令集。如果要使用真实设备运行本教程，请将:code:<a href="#id1"><span class="problematic" id="id2">`</span></a>local_demo`设置为False。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">local_demo</span> <span class="o">=</span> <span class="kc">True</span>

<span class="c1"># by default on CPU target will execute.</span>
<span class="c1"># select &#39;cpu&#39;, &#39;opencl&#39; and &#39;vulkan&#39;</span>
<span class="n">test_target</span> <span class="o">=</span> <span class="s2">&quot;cpu&quot;</span>

<span class="c1"># Change target configuration.</span>
<span class="c1"># Run `adb shell cat /proc/cpuinfo` to find the arch.</span>
<span class="n">arch</span> <span class="o">=</span> <span class="s2">&quot;arm64&quot;</span>
<span class="n">target</span> <span class="o">=</span> <span class="n">tvm</span><span class="o">.</span><span class="n">target</span><span class="o">.</span><span class="n">Target</span><span class="p">(</span><span class="s2">&quot;llvm -mtriple=</span><span class="si">%s</span><span class="s2">-linux-android&quot;</span> <span class="o">%</span> <span class="n">arch</span><span class="p">)</span>

<span class="k">if</span> <span class="n">local_demo</span><span class="p">:</span>
    <span class="n">target</span> <span class="o">=</span> <span class="n">tvm</span><span class="o">.</span><span class="n">target</span><span class="o">.</span><span class="n">Target</span><span class="p">(</span><span class="s2">&quot;llvm&quot;</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">test_target</span> <span class="o">==</span> <span class="s2">&quot;opencl&quot;</span><span class="p">:</span>
    <span class="n">target</span> <span class="o">=</span> <span class="n">tvm</span><span class="o">.</span><span class="n">target</span><span class="o">.</span><span class="n">Target</span><span class="p">(</span><span class="s2">&quot;opencl&quot;</span><span class="p">,</span> <span class="n">host</span><span class="o">=</span><span class="n">target</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">test_target</span> <span class="o">==</span> <span class="s2">&quot;vulkan&quot;</span><span class="p">:</span>
    <span class="n">target</span> <span class="o">=</span> <span class="n">tvm</span><span class="o">.</span><span class="n">target</span><span class="o">.</span><span class="n">Target</span><span class="p">(</span><span class="s2">&quot;vulkan&quot;</span><span class="p">,</span> <span class="n">host</span><span class="o">=</span><span class="n">target</span><span class="p">)</span>

<span class="n">input_name</span> <span class="o">=</span> <span class="s2">&quot;input_1&quot;</span>
<span class="n">shape_dict</span> <span class="o">=</span> <span class="p">{</span><span class="n">input_name</span><span class="p">:</span> <span class="n">x</span><span class="o">.</span><span class="n">shape</span><span class="p">}</span>
<span class="n">mod</span><span class="p">,</span> <span class="n">params</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">frontend</span><span class="o">.</span><span class="n">from_keras</span><span class="p">(</span><span class="n">keras_mobilenet_v2</span><span class="p">,</span> <span class="n">shape_dict</span><span class="p">)</span>

<span class="k">with</span> <span class="n">tvm</span><span class="o">.</span><span class="n">transform</span><span class="o">.</span><span class="n">PassContext</span><span class="p">(</span><span class="n">opt_level</span><span class="o">=</span><span class="mi">3</span><span class="p">):</span>
    <span class="n">lib</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">build</span><span class="p">(</span><span class="n">mod</span><span class="p">,</span> <span class="n">target</span><span class="o">=</span><span class="n">target</span><span class="p">,</span> <span class="n">params</span><span class="o">=</span><span class="n">params</span><span class="p">)</span>

<span class="c1"># After `relay.build`, you will get three return values: graph,</span>
<span class="c1"># library and the new parameter, since we do some optimization that will</span>
<span class="c1"># change the parameters but keep the result of model as the same.</span>

<span class="c1"># Save the library at local temporary directory.</span>
<span class="n">tmp</span> <span class="o">=</span> <span class="n">utils</span><span class="o">.</span><span class="n">tempdir</span><span class="p">()</span>
<span class="n">lib_fname</span> <span class="o">=</span> <span class="n">tmp</span><span class="o">.</span><span class="n">relpath</span><span class="p">(</span><span class="s2">&quot;net.so&quot;</span><span class="p">)</span>
<span class="n">fcompile</span> <span class="o">=</span> <span class="n">ndk</span><span class="o">.</span><span class="n">create_shared</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">local_demo</span> <span class="k">else</span> <span class="kc">None</span>
<span class="n">lib</span><span class="o">.</span><span class="n">export_library</span><span class="p">(</span><span class="n">lib_fname</span><span class="p">,</span> <span class="n">fcompile</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="deploy-the-model-remotely-by-rpc">
<h2>通过RPC远程部署模型<a class="headerlink" href="#deploy-the-model-remotely-by-rpc" title="永久链接至标题">¶</a></h2>
<p>使用RPC，您可以将模型从主机远程部署到远程android设备。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">tracker_host</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&quot;TVM_TRACKER_HOST&quot;</span><span class="p">,</span> <span class="s2">&quot;127.0.0.1&quot;</span><span class="p">)</span>
<span class="n">tracker_port</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&quot;TVM_TRACKER_PORT&quot;</span><span class="p">,</span> <span class="mi">9190</span><span class="p">))</span>
<span class="n">key</span> <span class="o">=</span> <span class="s2">&quot;android&quot;</span>

<span class="k">if</span> <span class="n">local_demo</span><span class="p">:</span>
    <span class="n">remote</span> <span class="o">=</span> <span class="n">rpc</span><span class="o">.</span><span class="n">LocalSession</span><span class="p">()</span>
<span class="k">else</span><span class="p">:</span>
    <span class="n">tracker</span> <span class="o">=</span> <span class="n">rpc</span><span class="o">.</span><span class="n">connect_tracker</span><span class="p">(</span><span class="n">tracker_host</span><span class="p">,</span> <span class="n">tracker_port</span><span class="p">)</span>
    <span class="c1"># When running a heavy model, we should increase the `session_timeout`</span>
    <span class="n">remote</span> <span class="o">=</span> <span class="n">tracker</span><span class="o">.</span><span class="n">request</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">priority</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">session_timeout</span><span class="o">=</span><span class="mi">60</span><span class="p">)</span>

<span class="k">if</span> <span class="n">local_demo</span><span class="p">:</span>
    <span class="n">dev</span> <span class="o">=</span> <span class="n">remote</span><span class="o">.</span><span class="n">cpu</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">test_target</span> <span class="o">==</span> <span class="s2">&quot;opencl&quot;</span><span class="p">:</span>
    <span class="n">dev</span> <span class="o">=</span> <span class="n">remote</span><span class="o">.</span><span class="n">cl</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">test_target</span> <span class="o">==</span> <span class="s2">&quot;vulkan&quot;</span><span class="p">:</span>
    <span class="n">dev</span> <span class="o">=</span> <span class="n">remote</span><span class="o">.</span><span class="n">vulkan</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="n">dev</span> <span class="o">=</span> <span class="n">remote</span><span class="o">.</span><span class="n">cpu</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>

<span class="c1"># upload the library to remote device and load it</span>
<span class="n">remote</span><span class="o">.</span><span class="n">upload</span><span class="p">(</span><span class="n">lib_fname</span><span class="p">)</span>
<span class="n">rlib</span> <span class="o">=</span> <span class="n">remote</span><span class="o">.</span><span class="n">load_module</span><span class="p">(</span><span class="s2">&quot;net.so&quot;</span><span class="p">)</span>

<span class="c1"># create the remote runtime module</span>
<span class="n">module</span> <span class="o">=</span> <span class="n">runtime</span><span class="o">.</span><span class="n">GraphModule</span><span class="p">(</span><span class="n">rlib</span><span class="p">[</span><span class="s2">&quot;default&quot;</span><span class="p">](</span><span class="n">dev</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="section" id="execute-on-tvm">
<h2>在 TVM 上执行<a class="headerlink" href="#execute-on-tvm" title="永久链接至标题">¶</a></h2>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># set input data</span>
<span class="n">module</span><span class="o">.</span><span class="n">set_input</span><span class="p">(</span><span class="n">input_name</span><span class="p">,</span> <span class="n">tvm</span><span class="o">.</span><span class="n">nd</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="n">x</span><span class="o">.</span><span class="n">astype</span><span class="p">(</span><span class="n">dtype</span><span class="p">)))</span>
<span class="c1"># run</span>
<span class="n">module</span><span class="o">.</span><span class="n">run</span><span class="p">()</span>
<span class="c1"># get output</span>
<span class="n">out</span> <span class="o">=</span> <span class="n">module</span><span class="o">.</span><span class="n">get_output</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>

<span class="c1"># get top1 result</span>
<span class="n">top1</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">argmax</span><span class="p">(</span><span class="n">out</span><span class="o">.</span><span class="n">numpy</span><span class="p">())</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;TVM prediction top-1: </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">synset</span><span class="p">[</span><span class="n">top1</span><span class="p">]))</span>

<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Evaluate inference time cost...&quot;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">module</span><span class="o">.</span><span class="n">benchmark</span><span class="p">(</span><span class="n">dev</span><span class="p">,</span> <span class="n">number</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">repeat</span><span class="o">=</span><span class="mi">10</span><span class="p">))</span>
</pre></div>
</div>
<p class="sphx-glr-script-out">输出:</p>
<div class="sphx-glr-script-out highlight-none notranslate"><div class="highlight"><pre><span></span>TVM prediction top-1: tiger cat
Evaluate inference time cost...
Execution time summary:
 mean (ms)   median (ms)    max (ms)     min (ms)     std (ms)
  18.5755      18.5228      19.3615      18.2058       0.3498
</pre></div>
</div>
</div>
<div class="section" id="sample-output">
<h2>样本输出<a class="headerlink" href="#sample-output" title="永久链接至标题">¶</a></h2>
<p>以下是Snapdragon 820上使用Adreno 530的 ‘cpu’, ‘opencl’ 和 ‘vulkan’ 的结果</p>
<p>虽然我们可以在GPU上运行，但它比CPU慢。为了加快速度，我们需要根据GPU架构编写和优化调度。</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="c1"># cpu</span>
TVM prediction top-1: tiger cat
Evaluate inference <span class="nb">time</span> cost...
Mean inference <span class="nb">time</span> <span class="o">(</span>std dev<span class="o">)</span>: <span class="m">37</span>.92 ms <span class="o">(</span><span class="m">19</span>.67 ms<span class="o">)</span>

<span class="c1"># opencl</span>
TVM prediction top-1: tiger cat
Evaluate inference <span class="nb">time</span> cost...
Mean inference <span class="nb">time</span> <span class="o">(</span>std dev<span class="o">)</span>: <span class="m">419</span>.83 ms <span class="o">(</span><span class="m">7</span>.49 ms<span class="o">)</span>

<span class="c1"># vulkan</span>
TVM prediction top-1: tiger cat
Evaluate inference <span class="nb">time</span> cost...
Mean inference <span class="nb">time</span> <span class="o">(</span>std dev<span class="o">)</span>: <span class="m">465</span>.80 ms <span class="o">(</span><span class="m">4</span>.52 ms<span class="o">)</span>
</pre></div>
</div>
<div class="sphx-glr-footer class sphx-glr-footer-example docutils container" id="sphx-glr-download-how-to-deploy-models-deploy-model-on-android-py">
<div class="sphx-glr-download docutils container">
<p><a class="reference download internal" download="" href="../../_downloads/21a9dd883b196be58ca1c5cd02700274/deploy_model_on_android.py"><code class="xref download docutils literal notranslate"><span class="pre">下载</span> <span class="pre">Python</span> <span class="pre">源代码:</span> <span class="pre">deploy_model_on_android.py</span></code></a></p>
</div>
<div class="sphx-glr-download docutils container">
<p><a class="reference download internal" download="" href="../../_downloads/eed2658f15243bab719b2de7769fa45a/deploy_model_on_android.ipynb"><code class="xref download docutils literal notranslate"><span class="pre">下载</span> <span class="pre">Jupyter</span> <span class="pre">notebook:</span> <span class="pre">deploy_model_on_android.ipynb</span></code></a></p>
</div>
</div>
<p class="sphx-glr-signature"><a class="reference external" href="https://sphinx-gallery.github.io">Gallery generated by Sphinx-Gallery</a></p>
</div>
</div>


           </div>
           
          </div>
          

<footer>

    <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
      
        <a href="deploy_model_on_rasp.html" class="btn btn-neutral float-right" title="在Raspberry Pi上部署预训练模型" accesskey="n" rel="next">下一个 <span class="fa fa-arrow-circle-right"></span></a>
      
      
        <a href="index.html" class="btn btn-neutral float-left" title="Deploy Deep Learning Models" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> 上一个</a>
      
    </div>

<div id="button" class="backtop"><img src="../../_static//img/right.svg" alt="backtop"/> </div>
<section class="footerSec">
    <div class="footerHeader">
      <ul class="d-flex align-md-items-center justify-content-between flex-column flex-md-row">
        <li class="copywrite d-flex align-items-center">
          <h5 id="copy-right-info">© 2020 Apache Software Foundation | All right reserved</h5>
        </li>
      </ul>

    </div>

    <ul>
      <li class="footernote">Copyright © 2020 The Apache Software Foundation. Apache TVM, Apache, the Apache feather, and the Apache TVM project logo are either trademarks or registered trademarks of the Apache Software Foundation.</li>
    </ul>

</section>
</footer>
        </div>
      </div>

    </section>

  </div>
  

    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

  </body>
  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script>

  
  
    
    <!-- Theme Analytics -->
    <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-75982049-2', 'auto');
    ga('send', 'pageview');
    </script>

    
   

</body>
</html>